package com.qf.electronic.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.electronic.dto.InspectionReceptionDto;
import com.qf.electronic.dto.InspectionReceptionStateDto;
import com.qf.electronic.pojo.Inspection;
import com.qf.electronic.pojo.InspectionReception;
import com.qf.electronic.mapper.InspectionReceptionMapper;
import com.qf.electronic.service.IDefectTaskService;
import com.qf.electronic.service.IInspectionReceptionService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.electronic.service.IInspectionService;
import com.qf.electronic.vo.InspectionReceptionVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wu
 * @since 2023-05-04
 */
@Service
public class InspectionReceptionServiceImpl extends ServiceImpl<InspectionReceptionMapper, InspectionReception> implements IInspectionReceptionService {

    @Autowired
    private IDefectTaskService defectTaskService;

    @Autowired
    private IInspectionService inspectionService;

    @Transactional(readOnly = true, isolation = Isolation.READ_COMMITTED)
    @Override
    public Page<InspectionReceptionVo> searchInspectionReceptions(InspectionReceptionDto receptionDto) {
        Page<InspectionReceptionVo> page = new Page<>(receptionDto.getCurrentPage(), receptionDto.getPageSize());
        return this.baseMapper.getInspectionReceptions(page, receptionDto);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean changeInspectionReceptionState(InspectionReceptionStateDto stateDto) {
        Integer state = stateDto.getState();
        UpdateWrapper<InspectionReception> wrapper = new UpdateWrapper<>();
        wrapper.set("state", state);
        wrapper.eq("id", stateDto.getId());
        if (update(wrapper)) {//状态修改成功 且状态为审核通过
            if(state == 2){
                //产生消缺任务
                boolean result1 = defectTaskService.addDefectTask(stateDto);
                //这个查询主要是查询巡检任务的ID出来
                InspectionReception inspectionReception = getById(stateDto.getId());
                UpdateWrapper<Inspection> inspectionWrapper = new UpdateWrapper<>();
                //更改巡检任务状态为已完成
                inspectionWrapper.set("state", 3);//完成状态
                inspectionWrapper.eq("id", inspectionReception.getInspectionId());
                boolean result2 = inspectionService.update(inspectionWrapper);
                return result1 && result2;
            }
           return true;
        }
        return false;
    }
}
